package zcw.com.lib_leet_code;

import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2022/1/27.<br><br>
 *
 * 中等：轮转数组
 */
public class Topic189 {

    public static void main(String[] args) {
        BaseSolution solution = new Solution2();

        int[] array = new int[] {1,2,3,4,5,6,7};
        solution.rotate(array, 3);
        Util.printArray(array);

        array = new int[] {-1,-100,3,99};
        solution.rotate(array, 2);
        Util.printArray(array);

        array = new int[] {-1};
        solution.rotate(array, 2);
        Util.printArray(array);
    }

    private interface BaseSolution {
        void rotate(int[] nums, int k);
    }

    private static class Solution1 implements BaseSolution {

        @Override
        public void rotate(int[] nums, int k) {
            if(nums.length < 2) {
                return ;
            }

            k = k % nums.length;
            helper(nums, 0, nums.length - 1);
            helper(nums, 0, k - 1);
            helper(nums, k, nums.length - 1);
        }

        private void helper(int[] nums, int start, int end) {
            if(start >= end) {
                return ;
            }

            while (start < end) {
                int temp = nums[start];
                nums[start] = nums[end];
                nums[end] = temp;

                start++;
                end--;
            }
        }
    }

    private static class Solution2 implements BaseSolution {

        @Override
        public void rotate(int[] nums, int k) {
            int len = nums.length;

            if(k == 0 || k % len == 0) {
                return ;
            }

            k = k % len;
            int[] array = new int[k];
            if (k >= 0) System.arraycopy(nums, len - k, array, 0, k);

            if (len - k - 1 + 1 >= 0) System.arraycopy(nums, 0, nums, k, len - k - 1 + 1);

            if (k >= 0) System.arraycopy(array, 0, nums, 0, k);
        }
    }
}
